<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridProps } from '#/adapter/vxe-table'
import TableAction from '#/components/TableAction/index.vue'
import { useTableList } from '#/hooks/useTableList'
import { $t } from '@vben/locales'
import { downloadFileFromUrl, formatDate } from '@vben/utils'
import { columns, formSchema } from '../data/table'

const props = withDefaults(
    defineProps<{
        api: (...args: any[]) => Promise<any>
        pageHeight?: string
        queryParams?: Record<string, any>
    }>(),
    {
        queryParams: () => ({}),
        pageHeight: undefined
    }
)

const formOptions: VbenFormProps = {
    schema: formSchema,
    fieldMappingTime: [['createTime', ['startTime', 'endTime'], 'YYYY-MM-DD HH:mm:ss']]
}

const gridOptions: VxeGridProps<any> = {
    height: props.pageHeight,
    columns,
    proxyConfig: {
        ajax: {
            query: async ({ page }, formValues) => {
                if (formValues.checkStartTime && formValues.checkEndTime) {
                    formValues.checkStartTime = `${formatDate(formValues.checkStartTime, 'YYYY-MM-DD')} 00:00:00`
                    formValues.checkEndTime = `${formatDate(formValues.checkEndTime, 'YYYY-MM-DD')} 23:59:59`
                }
                const res = await props.api({
                    ...formValues,
                    ...props.queryParams,
                    limit: page.pageSize,
                    page: page.currentPage
                })
                return {
                    items: res.records,
                    total: res.total
                }
            }
        }
    }
}

/**
 * 表格配置
 */
const { Grid, GridApi, reload } = useTableList({
    formOptions,
    gridOptions
})

function downloadErrorReport(record: Record<string, any>) {
    downloadFileFromUrl({
        source: record.url
    })
}

/**
 * table 操作
 * @param record
 */
function getActions(record: Record<string, any>) {
    const arr: any[] = []

    if (record.url) {
        arr.push({
            label: $t('common.downloadErrorReport'),
            onClick: () => {
                downloadErrorReport(record)
            }
        })
    }

    return arr
}

defineExpose({
    GridApi,
    reload
})
</script>

<template>
    <Grid>
        <template #action="{ row }">
            <TableAction :actions="getActions(row)" />
        </template>
    </Grid>
</template>
